package com.zyx.netty.server;

import com.zyx.netty.codec.RequestHttpDecoder;
import com.zyx.netty.handler.DeviceResponseHandler;
import com.zyx.netty.handler.DeviceRequestHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.zyx.constants.Constants.*;

/**
 * 描述说明:
 *
 * @author DQing
 * @version 1.0
 * @className ControlChannelInitializer
 * @date 2020/3/24 11:26
 */
@Slf4j
@Component
public class DeviceChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Value("${netty.device.read-timeout}")
    private int readTimeOut;
    @Autowired
    DeviceRequestHandler deviceRequestHandler;
    @Autowired
    DeviceResponseHandler deviceResponseHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new LoggingHandler());
        pipeline.addLast(
                new IdleStateHandler(readTimeOut, 0, 0, TimeUnit.MINUTES));
        pipeline.addLast(DECODER_HANDLER,new RequestHttpDecoder());
        pipeline.addLast(new HttpObjectAggregator(1024*1024*1024));
        pipeline.addLast(REQUEST_HANDLER,deviceRequestHandler);
        pipeline.addLast(RESPONSE_HANDLER,deviceResponseHandler);
    }

}
